//
//  MXNewViewVC.m
//  MXの衣柜
//
//  Created by 马霄 on 15/8/7.
//  Copyright (c) 2015年 霄 马. All rights reserved.
//

#import "MXNewViewVC.h"
#import "UIView+Extension.h"
#import "MXNewViewShopsTableViewCell.h"
#import "AFNetworkHandler.h"
#import "MXProductsModel.h"
#import "MXFindWebViewVC.h"
#import "MXDropdownMenu.h"
#import "MXNewViewTitleMenuVC.h"
#import "MXNewViewTitleMenuTableViewController.h"
#import "Height.h"
#import "MJRefresh.h"
#import "MBProgressHUD.h"

@interface MXNewViewVC ()<UITableViewDataSource, UITableViewDelegate, MXDropdownMenuDelegate, MXNewViewTitleMenuVCDelegate>
@property (nonatomic, retain) UITableView *tableView;
//--------------------- 设置全局数组 ---------------------
@property (nonatomic, retain) NSMutableArray *shopArray;
@property (nonatomic, retain) NSMutableArray *infoArray;
@property (nonatomic, retain) NSMutableArray *productsArray;
@property (nonatomic, retain) NSMutableArray *imageArray;
//测试
@property (nonatomic, retain) NSMutableArray *ProducArray;
//--------------------- 自定义TableViewCell 设成全局属性 用于传值 ---------------------

@property (nonatomic, retain) NSString *TmallLinkString;

@property (nonatomic, retain) NSMutableArray *TmallLinkArr;

@property (nonatomic, assign) NSInteger tempSection;

@property (nonatomic, retain) NSString *shopTag;

@property (nonatomic, assign) NSInteger pageNum;

@property (nonatomic, retain) UIImageView *background;

@property (nonatomic, assign) BOOL hidden;
@property (nonatomic, retain) MBProgressHUD *HUD;

@property (nonatomic, retain) UIView *alterView;

@property (nonatomic, retain) UIButton *titleButton;
@end

@implementation MXNewViewVC
- (void)dealloc
{
    [_titleButton release];
    [_HUD release];
    [_alterView release];
    [_background release];
    [_shopTag release];
    [_TmallLinkArr release];
    [_TmallLinkString release];
    [_ProducArray release];
    [_imageArray release];
    [_productsArray release];
    [_infoArray release];
    [_shopArray release];
    [_tableView release];
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.TmallLinkArr = [NSMutableArray array];
    }
    return self;
}
-(void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = NO;

}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.navigationController.navigationBarHidden = NO;

    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"Home_titleBackGround"] forBarMetrics:UIBarMetricsDefault];
    
    self.navigationController.navigationBar.translucent = NO;
    /* 中间的标题按钮 */
    //    UIButton *titleButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.titleButton = [[UIButton alloc] init];
    self.titleButton.width = WIDTHPRO * 150;
    self.titleButton.height = HEIGHTPRO * 30;
    //    titleButton.backgroundColor = HWRandomColor;
    
    // 设置图片和文字
    if (self.shopTag) {
        [self.titleButton setTitle:self.shopTag forState:(UIControlStateNormal)];

    } else {
        [self.titleButton setTitle:@"店铺推荐" forState:UIControlStateNormal];
        
    }
    [self.titleButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    self.titleButton.titleLabel.font = [UIFont boldSystemFontOfSize:17];
    [self.titleButton setImage:[UIImage imageNamed:@"navigationbar_arrow_down"] forState:UIControlStateNormal];
    [self.titleButton setImage:[UIImage imageNamed:@"navigationbar_arrow_up"] forState:UIControlStateSelected];
    //    titleButton.imageView.backgroundColor = [UIColor redColor];
    //    titleButton.titleLabel.backgroundColor = [UIColor blueColor];
    
    CGSize textWid = [Height getTextSize:self.titleButton.titleLabel.text Wid:150 Font:17];
    
    self.titleButton.imageEdgeInsets = UIEdgeInsetsMake(0, WIDTHPRO * 25 + textWid.width, 0, 0);
    self.titleButton.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0, HEIGHTPRO * 40);
    
    // 监听标题点击
    [self.titleButton addTarget:self action:@selector(titleClick:) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.titleView = self.titleButton;
    // 如果图片的某个方向上不规则，比如有突起，那么这个方向就不能拉伸

    
    
    //全局数组初始化
    self.shopArray = [NSMutableArray array];
    self.infoArray = [NSMutableArray array];
    self.productsArray = [NSMutableArray array];
    self.imageArray = [NSMutableArray array];
    self.ProducArray = [NSMutableArray array];
//    self.TmallLinkArr = [NSMutableArray array];
    //添加表视图
//    [self creatTableView];
    
    // 设置首页tag为空 
    self.shopTag = @"";
    
    // 数据是动态的 需要先创建视图
    [self creatTableView];

    
    // 添加刷新方法
    [self loadingCollectionView];
    
    [self refreshTableView];
    
    
    //引入 店家数据
    [self GetShopsData];
    
    self.pageNum = 1;
    
    [self creatBackGroundImage];
    
    [self.view insertSubview:self.tableView aboveSubview:self.background];

    [self uiActivityindicatorviewStart];
    
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(uiActivityindicatorviewEnd) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
    // Do any additional setup after loading the view.
}

-(void)uiActivityindicatorviewStart
{
    self.alterView =[[[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)] autorelease];
    self.alterView.backgroundColor =[UIColor whiteColor];
    self.HUD = [MBProgressHUD showHUDAddedTo:self.alterView animated:YES];
//    self.HUD.labelText = @"正在努力的给您加载";
    [self.HUD show:YES];
    
    [self.view addSubview:self.alterView];
    
}
-(void)uiActivityindicatorviewEnd
{
    [self.alterView removeFromSuperview];
}

- (void)creatBackGroundImage
{
    self.background = [[UIImageView alloc] initWithFrame:self.view.bounds];
    self.background.image = [UIImage imageNamed:@"Home_background"];
    [self.view addSubview:self.background];
    
}


- (void)creatTableView
{
    self.tableView = [[[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - HEIGHTPRO * 49) style:(UITableViewStylePlain)] autorelease];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.tableView];
}

#pragma mark -- 下拉刷新
-(void)refreshTableView
{
    //    __block MXFindVC *findVC = self;
    [self.tableView addHeaderWithCallback:^{
        //        [self GetFindData];
        [self.tableView headerEndRefreshing];
    }];
    //添加下拉刷新头部控件
    
    //    [self.collectionView reloadData];
}

#pragma mark -- 上拉加载

-(void)loadingCollectionView
{
    
    //    __unsafe_unretained typeof(self) vc = self;
    [self.tableView addFooterWithCallback:^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            NSString *shopsPath = [NSString stringWithFormat:@"http://rm.app.hongniujia.com/json_shop.php?action=list&ver=1&page=%ld&tag=%@&pageSize=20&appCookie=channel_AppStore%%20version_6.11%%20oid_AE53CF37-EAEB-468C-8507-15A922FDD348%%20package_com.aslibra.rm.nanren%%20platform_iphone%%20ver_8.4%%20jb_0%%20t1_1438909514%%20md5_db%%20t_1438671553", (long)self.pageNum, self.shopTag];
            self.pageNum += 1;
            //    shopsPath = [shopsPath stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            
            
            [AFNetworkHandler GETwithUTF8AFNByURL:shopsPath completion:^(id result) {
                NSArray *dataArr = [result objectForKey:@"data"];
//                [self.shopArray removeAllObjects];
//                [self.TmallLinkArr removeAllObjects];
//                [self.productsArray removeAllObjects];
//                [self.infoArray removeAllObjects];
                for (NSDictionary *dataDict in dataArr) {
                    MXNewViewDataModel *dataModel = [[[MXNewViewDataModel alloc] initWithDic:dataDict] autorelease];
                    [self.shopArray addObject:dataModel];
                    
                    //========================== Info数据 ===================================
                    NSDictionary *infoDict = dataModel.info;
                    
                    MXNewViewDataModel *infoModel = [[MXNewViewDataModel alloc] initWithDic:infoDict];
                    
                    [self.infoArray addObject:infoModel];
                    
                    [self.productsArray addObject:dataModel.products];
                    
                    [self.TmallLinkArr addObject:dataModel.shopUrl];
                    
                }
                //========================== CollectionView 商品数据 ===================================
                
                //        NSLog(@"%@", self.ProducArray);
                
                //        NSLog(@"%ld", self.productsArray.count);
                
//                NSLog(@"%@", self.TmallLinkArr);
                
                //        [self.tableView reloadData];
                
            }];

            [self.tableView reloadData];
            [self.tableView footerEndRefreshing];
        });
    }];
}



/************************ 店铺部分数据解析 *******************************/
- (void)GetShopsData
{
    NSString *shopsPath = [NSString stringWithFormat:@"http://rm.app.hongniujia.com/json_shop.php?action=list&ver=1&page=0&tag=%@&pageSize=20&appCookie=channel_AppStore%%20version_6.11%%20oid_AE53CF37-EAEB-468C-8507-15A922FDD348%%20package_com.aslibra.rm.nanren%%20platform_iphone%%20ver_8.4%%20jb_0%%20t1_1438909514%%20md5_db%%20t_1438671553", self.shopTag];
    
    [AFNetworkHandler GETwithUTF8AFNByURL:shopsPath completion:^(id result) {
        NSArray *dataArr = [result objectForKey:@"data"];
        [self.shopArray removeAllObjects];
        [self.TmallLinkArr removeAllObjects];
        [self.productsArray removeAllObjects];
        [self.infoArray removeAllObjects];
        for (NSDictionary *dataDict in dataArr) {
            MXNewViewDataModel *dataModel = [[[MXNewViewDataModel alloc] initWithDic:dataDict] autorelease];
            [self.shopArray addObject:dataModel];
            
//========================== Info数据 ===================================
            NSDictionary *infoDict = dataModel.info;
            
            MXNewViewDataModel *infoModel = [[MXNewViewDataModel alloc] initWithDic:infoDict];
            
            [self.infoArray addObject:infoModel];
            
            [self.productsArray addObject:dataModel.products];
            
            [self.TmallLinkArr addObject:dataModel.shopUrl];
        
        }
//========================== CollectionView 商品数据 ===================================
        
        
        [self.tableView reloadData];
        
        [self uiActivityindicatorviewEnd];
    }];
}
#pragma mark - 下拉菜单点击方法
/**
 *  标题点击
 */
- (void)titleClick:(UIButton *)titleButton
{
    // 1.创建下拉菜单
    MXDropdownMenu *menu = [MXDropdownMenu menu];
    menu.delegate = self;
    
    // 2.设置内容
    MXNewViewTitleMenuVC *vc = [[MXNewViewTitleMenuVC alloc] init];
    vc.delegate = self;
    menu.y = 0;
    menu.x = 0;
    
    vc.view.height = HEIGHTPRO * 300;
    vc.view.width = WIDTHPRO * 200;
    menu.contentController = vc;
    
    // 3.显示
    [menu showFrom:titleButton];
    
    

    
    

}

/************************* TableView Delegate **************************/
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.shopArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}


#pragma mark - HWDropdownMenuDelegate
/**
 *  下拉菜单被销毁了
 */
- (void)dropdownMenuDidDismiss:(MXDropdownMenu *)menu
{
    UIButton *titleButton = (UIButton *)self.navigationItem.titleView;
    titleButton.selected = NO;
    // 让箭头向下
    //    [titleButton setImage:[UIImage imageNamed:@"navigationbar_arrow_down"] forState:UIControlStateNormal];
}

/**
 *  下拉菜单显示了
 */
- (void)dropdownMenuDidShow:(MXDropdownMenu *)menu
{
    UIButton *titleButton = (UIButton *)self.navigationItem.titleView;
    titleButton.selected = YES;
    // 让箭头向上
    //    [titleButton setImage:[UIImage imageNamed:@"navigationbar_arrow_up"] forState:UIControlStateNormal];
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
#pragma mark - tableView 数据部分
    
    MXNewViewShopsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse"];
    if (!cell) {
        
        cell = [[MXNewViewShopsTableViewCell alloc] initWithStyle:(UITableViewCellStyleValue1) reuseIdentifier:@"reuse"];
    
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
#warning 感觉还是应该通过section进行传值
    [cell GetDetailInfo:self.infoArray[indexPath.section]];
    
    [cell GetInfo:self.shopArray[indexPath.section]];
    
    cell.viewContrller = self;
    
    self.tempSection = indexPath.section;
    
    
    self.TmallLinkString = self.TmallLinkArr[indexPath.section];

    
#pragma mark - collectionView 数据部分
    NSMutableArray *arr = [NSMutableArray array];
    
    for (NSDictionary *dict in self.productsArray[indexPath.section]) {
        
        MXProductsModel *model = [[[MXProductsModel alloc] initWithDic:dict] autorelease];
        
        [arr addObject:model];
        
    }
#warning TableView和CollectionView嵌套的时候需要reloadData 保证数据是最新的
    
    cell.tempArray = arr;
    
    [cell.collectionView reloadData];
    
//    [cell.control addTarget:self action:@selector(jumpTmallwith:) forControlEvents:(UIControlEventTouchUpInside)];
    
    cell.selected = NO;
    
    cell.navi = self.navigationController;
    
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return HEIGHTPRO * 320;
}

#pragma mark - TableView 点击方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)getShopTag:(NSString *)shopTag select:(BOOL)isSelected
{
    self.shopTag = shopTag;
    [self.titleButton setTitle:shopTag forState:(UIControlStateNormal)];
    [self GetShopsData];

    self.hidden = isSelected;
    
}
#pragma mark - 开始拖拽
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    self.tabBarController.tabBar.hidden = YES;
}
#pragma mark - 结束减速
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    self.tabBarController.tabBar.hidden = NO;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
